package netty.decoder.linebasedframedecoder.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeClientHandler extends ChannelHandlerAdapter {

	private int count = 0;
	
	private byte [] req;
	
	public TimeClientHandler() {
		req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		for(int i=0; i<100;i++){
			
			ByteBuf bb;
			bb = Unpooled.buffer(req.length);
			
			bb.writeBytes(req);
			ctx.writeAndFlush(bb);
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
//		ByteBuf bf = (ByteBuf) msg;
//		byte []  by = new byte[bf.readableBytes()];
//		bf.readBytes(by);
//		String body = new String(by,"UTF-8");
		String body = (String) msg;
		System.out.println("now is " + body + ",counter:" + ++count);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		System.out.println(cause.toString());
		ctx.close();
	}

}
